package com.example.gobang.api;

import com.example.gobang.game.MatchRequest;
import com.example.gobang.game.MatchResponse;
import com.example.gobang.game.Matcher;
import com.example.gobang.game.OnlineUserManager;
import com.example.gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class MatchAPI extends TextWebSocketHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private Matcher matcher;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("afterConnectionEstablished");

        try {
            User user = (User) session.getAttributes().get("user");
//
//            if(onlineUserManager.getFromGameHall(user.getUserId()) != null
//                    || onlineUserManager.getFromGameRoom(user.getUserId()) != null) {
//                MatchResponse response = new MatchResponse();
//                response.setOk(true);
//                response.setMessage("当前禁止多开!");
//                response.setMessage("repeatConnection");
//                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
////                session.close();
//                return;
//            }


            onlineUserManager.enterGameHall(user.getUserId(),session);
            System.out.println("玩家" + user.getUsername() + "进入游戏大厅!");
        }catch (NullPointerException e){
            System.out.println("[MatchAPI.afterConnectionEstablished] 当前用户未登录!");

            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("您尚未登录!不能进行后续匹配功能!");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("handleTextMessage");
              User user = (User) session.getAttributes().get("user");

              String payload = message.getPayload();

              MatchRequest request = objectMapper.readValue(payload,MatchRequest.class);
              MatchResponse response = new MatchResponse();
              if(request.getMessage().equals("startMatch")) {
                  matcher.add(user);
                  response.setOk(true);
                  response.setMessage("startMatch");
              }else if(request.getMessage().equals("stopMatch")) {
                  matcher.remove(user);
                  response.setOk(true);
                  response.setMessage("stopMatch");
              }else {
                  response.setOk(false);
                  response.setReason("非法的匹配请求!");
              }
              String jsonString = objectMapper.writeValueAsString(response);
              session.sendMessage(new TextMessage(jsonString));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("handleTransportError");
        try {
            User user = (User) session.getAttributes().get("user");
            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserId());
            if(tmpSession == session){
                onlineUserManager.exitGameHall(user.getUserId());
            }
            matcher.remove(user);
        }catch (NullPointerException e){
            System.out.println("[MatchAPI.handleTransportError当前用户未登录!]");

//            e.printStackTrace();

//            MatchResponse response = new MatchResponse();
//            response.setOk(false);
//            response.setReason("您尚未登录!不能进行后续匹配功能!");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("afterConnectionClosed");

        try {
            User user = (User) session.getAttributes().get("user");

            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserId());
            if(tmpSession == session){
                onlineUserManager.exitGameHall(user.getUserId());
            }
            matcher.remove(user);

        }catch (NullPointerException e){

            System.out.println("[MatchAPI.afterConnectionClosed当前用户未登录!]");
//            e.printStackTrace();

//            MatchResponse response = new MatchResponse();
//            response.setOk(false);
//            response.setReason("您尚未登录!不能进行后续匹配功能!");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }


}
